import re
import time
import base64
from ddddocr import DdddOcr
from selenium.webdriver.common.by import By
from taobao_check.tools import click_by_js
from .base import BaseBrush


class Marking(BaseBrush):
    login_url = "https://www.yihemeicn.com/Seller/login"
    index_url = "https://www.yihemeicn.com/Seller/index"
    check_url = "https://www.yihemeicn.com/Seller/task/index"

    def __init__(self, config, tab):
        super().__init__("精准打标", "marking", config, tab)
        self.ocr = DdddOcr()
        self.last_one = "1"
        self.last_two = "w"

    def login(self):
        while True:
            if self.browser.current_url != self.login_url:
                self.browser.get(self.login_url)

            text_input, verifi_input = self.find_elements((By.CSS_SELECTOR, 'input[type="text"]'))
            self.enter_text(text_input, self.username)
            self.enter_text((By.CSS_SELECTOR, 'input[type="password"]'), self.password)
            # 调用OCR识别验证码
            img_elment = self.find_element((By.CSS_SELECTOR, 'div[class="el-image"]>img'))
            img_src = img_elment.get_attribute('src')
            base64_data = re.sub('^data:image/.+;base64,', '', img_src)
            img_data = base64.b64decode(base64_data)
            code = self.ocr.classification(img_data).lower()
            if not code:
                self.browser.get(self.login_url)
                continue
            self.enter_text(verifi_input, code)
            self.click_button((By.CSS_SELECTOR, 'button[type="button"]'))

            if self.wait_login(3):
                break

    def click_ok(self):
        # 点击弹出框
        try:
            self.click_button((By.CSS_SELECTOR, "div.el-message-box__btns>button"), timeout=3)
        except:
            pass

    def check_user(self):
        # 等待页面加载
        self.print_log("marking check...", debug=True)
        self.click_ok()
        table = self.find_elements((By.CSS_SELECTOR, "div.el-card__body"))
        start = time.time()
        while len(table) <= 2:
            if time.time() - start > 10:
                self.print_log("页面加载超时，即将重试.", debug=True)
                return False
            table = self.find_elements((By.CSS_SELECTOR, "div.el-card__body"))
            time.sleep(1)

        # 切换到待审核界面
        self.click_button((By.CSS_SELECTOR, "i.el-icon-news"))
        time.sleep(2)
        self.click_ok()
        table = self.find_elements((By.CSS_SELECTOR, "div.el-card__body"))
        if len(table) <= 2:
            self.print_log("没有买号.", debug=True)
            self.sleep(self.refresh_time)
            return False

        try:
            # 由于处理后页面会自动刷新，因此每次只处理一个
            div = table[-2]
            text = div.find_element_by_css_selector("div.el-col-3>p>span").get_attribute('textContent').strip()
        except Exception as e:
            return True

        if text != "待审核":
            self.print_log("没有买号.", debug=True)
            self.sleep(self.refresh_time)
            return False

        self.print_log("发现待验买号.")
        username = div.find_elements_by_css_selector("div.text-info")[1].find_element_by_css_selector("p>span>span")
        username = username.get_attribute('textContent').strip()
        self.print_log(f"当前待验买号为：【{username}】")

        if self.last_one == self.last_two == username:
            self.print_log("买号为系统自动通过号.")
            result = True
        else:
            start = time.time()
            result = self.check.check_user(username, self.print_log)
            self.print_log(f"验号结果为: {'通过' if result else '不通过'}. 用时: {time.time() - start:.2f}s")

        buttons = div.find_elements_by_css_selector("div.el-col-3>p>button")
        rematch_button, start_button = buttons[0], buttons[1]
        if result:
            click_by_js(self.browser, start_button)
            self.click_button((By.CSS_SELECTOR, "div.el-message-box__btns>button.el-button--primary"))
            self.print_log("开始任务.\n")
        else:
            click_by_js(self.browser, rematch_button)
            self.click_button((By.CSS_SELECTOR, "div.el-message-box__btns>button.el-button--primary"))
            self.print_log("开始重新匹配买号.\n")

        self.last_two = self.last_one
        self.last_one = username
        self.sleep(2)
        return True
